# -*- coding: utf-8 -*-
import random
import yanchengMJ_v5
import requests
import time

MOP_NONE = -1 #无法做动作
MOP_PASS = 0  #过
MOP_LCHI = 1  #左吃
MOP_MCHI = 2  #中吃
MOP_RCHI = 3  #下吃
MOP_PENG = 4  #碰
MOP_MGANG = 5
MOP_AGANG = 6
MOP_BGANG = 7

input_pre = []  # 记录本手之前的输入特征
output_pre = []  # 记录本手之前的输出结果


def trans10to16(i):
    """0-33 to
    0x01-0x09
    0x11-0x19
    0x21-0x29
    0x31-0x37
    10 to 16 in mahjong
    :param i:
    :return:
    """
    if i >= 0 and i <= 8:  #0-8to1-9
        i += 1
    elif i >= 9 and i <= 17:  #9-17to17-25
        i = i + 8
    elif i >= 18 and i <= 26: #18-26to33-41
        i = i + 15
    elif i >= 27 and i <= 33:#27-33to49-55
        i = i + 22
    return i

#print(trans10to16(33))

def translate1_37to0_33(i):
    if i >= 1 and i <= 9:  #1-9to0-8
        i = i - 1
    elif i >= 11 and i <= 19: #11-19to9-17
        i = i - 2
    elif i >= 21 and i <= 29:  #21-29to19-27
        i = i - 2
    elif i >= 31 and i <= 37: #31-37to28-34
        i = i - 3
    else:
        print ("translate1_37to0_33 is error,i=%d" % i)
        i = 34
    return i

#print(translate1_37to0_33(0))

def RecommendCard_yanchengMJ_v5(input={}):
    user_cards = input.get('user_cards', {})
    catch_card = input.get('catch_card', 0)
    baida_card = input.get('baida_card', 0)
    fei_baida = input.get('fei_baida', 0)
    seat_id = input.get('seat_id', 0)
    discards = input.get('discards', [])
    discards_real = input.get('discards_real',[])
    discards_op = input.get('discards_op', [])
    remain_num = input.get('remain_num', 136)

    hands = input.get('hands',[])
    wall = input.get('wall',[])

    round = input.get('round', [])
    hand_cards = user_cards.get('hand_cards', [])
    operate_cards = user_cards.get('operate_cards', [])
    hand_cards.sort()
    [e.sort() for e in operate_cards]
    recommendCard = yanchengMJ_v5.recommend_card(cards=hand_cards, suits=operate_cards, baida_card=baida_card,
                                                 discards=discards, discards_op=discards_op,
                                                 remain_num=remain_num, round=round, seat_id=seat_id)
    return recommendCard

def RecommendOprate_yanchengMJ_v5(input={}):
    user_cards = input.get('user_cards', {})
    out_card = input.get('out_card', 0)
    baida_card = input.get('baida_card', 0)
    fei_baida = input.get('fei_baida', 0)
    discards_op = input.get('discards_op', [])
    discards_real = input.get('discards_real', [])
    remain_num = input.get('remain_num', 0)
    isHu=input.get('isHu',False)
    seat_id = input.get('seat_id', 0)
    out_seat_id = input.get('out_seat_id', 0)
    discards = input.get('discards', [])
    round = input.get('round',0)

    hands = input.get('hands', [])
    wall = input.get('wall', [])

    hand_cards = user_cards.get('hand_cards', [])
    operate_cards = user_cards.get('operate_cards', [])
    # discards = trandfer_discards(discards, hand_cards)  # 转化弃牌表
    hand_cards.sort()
    [e.sort() for e in operate_cards]
    recommend_op, isHu = yanchengMJ_v5.recommend_op(op_card=out_card, cards=hand_cards, suits=operate_cards,
                                                    baida_card=baida_card, discards=discards, discards_op=discards_op,
                                                    canchi=canchi(seat_id, out_seat_id), self_turn=(len(hand_cards) % 3 == 2),
                                                    isHu=isHu, round=round)
    return recommend_op,isHu

def trandfer_discards(discards, handcards):#discards弃牌堆，handcards手牌 记录所有可见牌
    discards_map = {
        0x01: 0,
        0x02: 1,
        0x03: 2,
        0x04: 3,
        0x05: 4,
        0x06: 5,
        0x07: 6,
        0x08: 7,
        0x09: 8,
        0x11: 9,
        0x12: 10,
        0x13: 11,
        0x14: 12,
        0x15: 13,
        0x16: 14,
        0x17: 15,
        0x18: 16,
        0x19: 17,
        0x21: 18,
        0x22: 19,
        0x23: 20,
        0x24: 21,
        0x25: 22,
        0x26: 23,
        0x27: 24,
        0x28: 25,
        0x29: 26,
        0x31: 27,
        0x32: 28,
        0x33: 29,
        0x34: 30,
        0x35: 31,
        0x36: 32,
        0x37: 33,
    }

    discards_list = [0] * 34

    for item in discards:
        discards_list[discards_map[item]] += 1
    for item in handcards:
        discards_list[discards_map[item]] += 1

    return discards_list

# 判断是否可吃.仅仅通过座位判断
def canchi(seat_id, out_seat_id):
    if seat_id == 0:
        if out_seat_id == 3:
            return True
        else:
            return False
    else:
        if seat_id == out_seat_id + 1:
            return True
        else:
            return False

def canpeng(out_card, hand_cards):
    return hand_cards.count(out_card) >= 2

def translate_index_to_hex(i):  # 1-34转换到16进制的card
    """
    将１－３４转化为牌值
    :param i:
    :return:
    """
    if i>=0 and i<=8:
        i=i+1
    if i >= 9 and i <= 17:
        i = i + 8
    elif i >= 18 and i <= 26:
        i = i + 15
    elif i >= 27 and i <= 33:
        i = i + 22
    return i

def test_time():
    # 耗时测试
    handCardsSet = []
    # 随机生成１００手手牌信息
    for i in range(100):
        handCards = []
        for j in random.sample(range(1, 137), 14):
            handCards.append(translate_index_to_hex(j / 4))
        handCardsSet.append(handCards)
    f = open('log.txt', 'w')

    i = 0  # 几率手数
    start = time.time()
    f.write('总开始时间:' + str(start) + '\n')
    for handCards in handCardsSet:
        request['user_cards']['hand_cards'] = handCards
        s = time.time()
        out_card = RecommendCard_yanchengMJ_v5(request)
        e = time.time()
        u = e - s
        i = i + 1
        f.write('第' + str(i) + '手:\n')
        f.write('开始时间:' + str(s) + '\n')
        f.write('手牌:' + str(handCards) + '\n')
        f.write('出牌:' + str(out_card) + '\n')
        f.write('结束时间：' + str(e) + '\n')
        f.write('耗时：' + str(u) + '\n\n')

    end = time.time()
    use_time = end - start
    avg_time = float(use_time) / 100
    f.write('总结束时间：' + str(end) + '\n')
    f.write('总耗时：' + str(use_time) + '\n')
    f.write('平均每手决策时间：' + str(avg_time) + '\n')
    f.write('平均每分钟决策次数：' + str(60.0 / avg_time) + '\n')

def request_interface():
    #
    import json

    # s = requests.session()
    # s.keep_alive = False
    url = "http://http://172.81.238.92:8085/yanchengMJ/v2/outcard"
    headers = {'Connection': 'close','Content-Type': 'application/json;charset=UTF-8'}
    requests.adapters.DEFAULT_RETRIES = 5
    # headers = {'Connection': 'close' }
    request_param = {"discards":[[52,54,50,41,7,39,2,17,9,8,3,34,23,7,6,37,54,6,18],[41,25,35,53,8,21,19,4,53,41,6,1,51,39,20,36,33,22],[50,54,51,9,33,25,20,36,18,52,40,21,24,2,39,4,55,55,33,54,7],[50,52,51,17,55,5,21,52,41,39,3,40,17,9,36,22,23,50,49,55]],"discards_op":[[],[[33,34,35]],[[49,49,49],[25,24,23]],[]],"fei_baida":0,"isHu":False,"baida_card":18,"out_card":7,"out_seat_id":2,"remain_num":5,"round":20,"seat_id":3,"user_cards":{"hand_cards":[1,2,5,7,8,9,23,24,38,19,5,25,36],"operate_cards":[]}}
    ti=time.time()
    response = requests.post(url, data=json.dumps(request_param), headers=headers)
    tj=time.time()
    print('time=',tj-ti)

if __name__ == '__main__':
    random_numbers = []
    while len(random_numbers) < 14:
        # 从1到34的范围内随机选择一个数字
        num = random.randint(0, 33)

        # 如果该数字已经出现了4次，则重新选择
        if random_numbers.count(num) >= 4:
            continue

        random_numbers.append(num)

    #random_numbers = [2,3,4,6,11,11,11,14,14,14,16,17,18,20]

    #print(random_numbers)
    for i,e in enumerate(random_numbers):
        random_numbers[i] = trans10to16(e)
    random_numbers = [17,17,18,18,21,3,4,5,6,6,6,7,2,2]
    random_numbers.sort()
    print(random_numbers)


    request = {"discards":[[18,39], [33,41], [8,34], [41,3]],
               "discards_op":[[[]], [], [], []],
               "operate_cards" : [],
               "discards_real":[[],
                                [],
                                [],
                                []],
               "hands":[random_numbers,
                        [0],
                        [0],
                        [0]],
               "baida_card":2,
               "out_card":0,
               "out_seat_id":0,
               "round":0,
               "seat_id":0,
               "user_cards":{"hand_cards":random_numbers,
                             "operate_cards":[]},
                             "wall":[]}

    name = {1:'一筒', 2:'二筒', 3:'三筒', 4:'四筒', 5:'五筒', 6:'六筒', 7:'七筒', 8:'八筒', 9:'九筒',
            17:'一万', 18:'二万', 19:'三万', 20:'四万', 21:'五万', 22:'六万', 23:'七万',24: '八万', 25:'九万',
            33:'一条', 34:'二条', 35:'三条', 36:'四条', 37:'五条', 38:'六条', 39:'七条', 40:'八条', 41:'九条',
             49:'红中'}

    print('手牌：',end='')
    for key in request['hands'][0]:
        print(name[key],end=' ')

    print(' ')
    start = time.time()
    out_card = RecommendCard_yanchengMJ_v5(request)
    print ("out_card=", out_card)
    print('推荐出牌：', name[out_card])
    end = time.time()
    print()
    print("time=", end - start)

    request_op = {
        "discards": [[], [], [], []],
        "discards_op": [[[], []], [], [], []],
        "fei_baida": 0,
        "isHu": False,
        "baida_card": 2,
        "out_card": 19,
        "out_seat_id": 1,
        "remain_num": 28,
        "round": 15,
        "seat_id": 2,
        "user_cards": {"hand_cards": [2, 33, 17, 18, 3, 6, 6], "operate_cards": [[33, 34, 35], [1, 1, 1]]}}
    startop = time.time()
    print ("op=",RecommendOprate_yanchengMJ_v5(request_op))
    endop = time.time()
    print()
    print("time=", endop - startop)
